package com.javaee.web.servlet;
import java.io.IOException;
import java.util.Date;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javaee.ejb.entity.Conversation;
import com.javaee.ejb.entity.Employee;
import com.javaee.ejb.entity.Project;
import com.javaee.ejb.session.remote.ConversationManagerRemote;
import com.javaee.ejb.session.remote.EmployeeManagerRemote;
import com.javaee.ejb.session.remote.ProjectManagerRemote;
import com.javaee.web.HttpServletBase;
import com.javaee.web.SiteParameters;

/**
 * Servlet implementation class AddConversationServlet
 */
public class AddConversationServlet extends HttpServletBase {
	private static final long serialVersionUID = 1L;

	@EJB
	private ProjectManagerRemote projectManager;

	@EJB
	private EmployeeManagerRemote employeeManager;

	@EJB
	private ConversationManagerRemote conversationManager;

	/**
	 * @see HttpServletBase#HttpServletBase()
	 */
	public AddConversationServlet() {
		super();
	}

	@Override
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// Recuperation des parametres
		int projectId;
		int calledtId;

		try {
			projectId = Integer.parseInt(request.getParameter("projectId"));
			calledtId = Integer.parseInt(request.getParameter("calledId"));
		} catch (Exception e) {
			throw new ServletException(e.getMessage());
		}

		// Chargement des objets
		Project projet = projectManager.getById(projectId);
		Employee caller = currentEmployee;
		Employee called = employeeManager.getById(calledtId);

		// Creation de la conversation
		Conversation conversation = new Conversation();
		conversation.setStart(new Date());
		conversation.setEnd(null);
		conversation.setCalled(called);
		conversation.setCaller(caller);
		conversation.setProject(projet);
		conversation.setStatus(0);

		int conversationId = conversationManager.saveConversation(conversation);

		response.sendRedirect(SiteParameters.getServletPath("conversation")
				+ "?conversationId=" + conversationId);
	}
}